package com.example.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.common.to.es.SkuEsModel;
import com.example.gulimall.search.config.GulimallElasticSearchConfig;
import com.example.gulimall.search.constant.EsConstant;
import com.example.gulimall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {


    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //保存到es
         //1 给es中建立索引，product，建立好映射关系，我们已经在试图工具kibana中建立好了
        //2 给es保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //使用skuid作为数据的id
            indexRequest.id(skuEsModel.getSkuId().toString());
            //将要保存的数据转为json
            String s = JSON.toJSONString(skuEsModel);
            //将数据绑定到indexRequest
            indexRequest.source(s, XContentType.JSON);
            //将保存的数据添加到批量保存
            bulkRequest.add(indexRequest);

        }
        //批量保存到es
        System.out.println("es客户端："+restHighLevelClient.toString());
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        //TODO 如果批量有错误 有错误返回true，没有返回false
        boolean b = bulk.hasFailures();
        //收集保存的id
            List<Integer> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getItemId();
            }).collect(Collectors.toList());

        log.info("商品上架成功:{}", collect);
        return b;
    }
}
